package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "FilterDemo01", urlPatterns = { "/pages/blogg/*","*.htm" })

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化...");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器执行中...");
        // 得到req 和 res
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        // 避免页面乱码
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
        // 寻址和PW
        String ctxPath = request.getContextPath();
        PrintWriter pw = response.getWriter();
        // 获取url
        String url = request.getRequestURI();
        // 必要资源放行
        if (url.contains("/js") || url.contains("/img") || url.contains("/css") || url.contains(".jpg") || url.contains(".png") ){
            filterChain.doFilter(request, response);
        }
        // 登录判定
        // session值由BloggerController传入
        Object username = request.getSession().getAttribute("username");
        if (username == null) {
            pw.println("<img src='/web/image/filter.png'/>" + "你还没有登录，请先登录！3秒后回到登录页面..." );
            response.setHeader("refresh", "3;url=" + ctxPath + "/pages/LR/loginAndRegist.jsp");
        }else{
            filterChain.doFilter(request, response);
        }
    }
    @Override
    public void destroy() {
        System.out.println("过滤器销毁");
    }
}
